package com.xm.dao.background;

import com.xm.entity.Menu;
import com.xm.entity.Page;
import com.xm.exception.SqlErrorException;
import com.xm.util.BaseUtil;
import org.intellij.lang.annotations.Language;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜单Dao层
 *
 * @author 康文程
 * @date 2023-12-15 下午 06:29
 */
public class MenuDao extends BaseUtil {
    /**
     * 修改权限
     * 如果传了getAddressId则修改
     *
     * @param menu 权限实体类
     * @throws SqlErrorException SQL执行异常
     */
    public boolean addMenu(Menu menu) throws SqlErrorException {
        //修改收货地址
        @Language("sql")
        String sql = "UPDATE menu SET menu_name = ?, required_permissions = ?,  menu_default = ?, page_url = ? WHERE menu_id = ?";
        int id = executeUpdate(sql, menu.getMenuName(),menu.getRequiredPermissions(),menu.getMenuDefault(),menu.getPageUrl(),menu.getMenuId());
        return id != 0;

    }

    /**
     * 查询全部菜单
     *
     * @return 菜单列表
     */
    public List<Menu> findAll() {
        // SQL语句
        @Language("sql")
        String sql = "select * from menu order by menu_default asc";
        // 执行查询操作
        ResultSet rs = null;
        List<Menu> menuList = new ArrayList<>();
        try {
            // 执行查询操作
            rs = executeQuery(sql);
            // 遍历结果集
            while (rs.next()) {
                Menu menu = new Menu();
                menu.setMenuId(rs.getInt("menu_id"));
                menu.setMenuName(rs.getString("menu_name"));
                menu.setRequiredPermissions(rs.getString("required_permissions"));
                menu.setMenuDefault(rs.getInt("menu_default"));
                menu.setPageUrl(rs.getString("page_url"));
                menuList.add(menu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs);
        }
        return menuList;
    }

    /**
     * 分页查询
     *
     * @param pageNumber 分页页数
     * @param pageSize   每页数量
     * @return page<对象>
     */
    public Page<Menu> pagination(int pageNumber, int pageSize, String permissionsMc, String menuDefault) {
        Page<Menu> page = new Page<>();
        List<Menu> list = new ArrayList<>();
        @Language("sql")
        String countSql = "SELECT COUNT(*) FROM menu";
        @Language("sql")
        String dataSql = "SELECT * FROM menu where 1=1";
        if (permissionsMc != null) {
            if (isNumeric(permissionsMc)) {
                dataSql += " and menu_id like '%" + permissionsMc + "%'";
            } else {
                dataSql += " and menu_name like '%" + permissionsMc + "%'";
            }
        }
        if (menuDefault != null) {
            dataSql += " and " + menuDefault + "=menu_default";
        }
        dataSql += " LIMIT ?, ?";

        ResultSet countRs = null;
        ResultSet dataRs = null;
        try {
            // 查询总数
            countRs = executeQuery(countSql);
            if (countRs.next()) {
                int count = countRs.getInt(1);
                page.setCount(count);
                page.setTotalPages(pageSize);
            }

            // 分页查询数据
            int offset = (pageNumber - 1) * pageSize;
            dataRs = executeQuery(dataSql, offset, pageSize);
            while (dataRs.next()) {
                Menu menu = extractMenuFromResultSet(dataRs);
                list.add(menu);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(countRs);
            close(dataRs);
        }
        page.setData(list);
        page.setPageNumber(pageNumber);
        page.setPageSize(pageSize);
        return page;
    }

    /**
     * 查询的参数
     *
     * @param rs 查询结果集
     * @return 对象
     * @throws SQLException 抛出错误
     */
    private Menu extractMenuFromResultSet(ResultSet rs) throws SQLException {
        Menu menu = new Menu();
        menu.setMenuId(rs.getInt("menu_id"));
        menu.setMenuName(rs.getString("menu_name"));
        menu.setRequiredPermissions(rs.getString("required_permissions"));
        menu.setMenuDefault(rs.getInt("menu_default"));
        menu.setPageUrl(rs.getString("page_url"));
        return menu;
    }

    /**
     * 判断是不是数字
     *
     * @param str 字符串
     * @return turn 是数字，false 不是数字
     */
    public static boolean isNumeric(String str) {
        return str != null && str.matches("-?\\d+(\\.\\d+)?");
    }
}
